package com.ktjy.ktmall.servlet;

import com.alibaba.fastjson.JSONArray;
import com.ktjy.ktmall.entity.AjaxResult;
import com.ktjy.ktmall.entity.CategoryItem;
import com.ktjy.ktmall.service.CategoryItemService;
import com.ktjy.ktmall.service.impl.CategoryItemServiceImpl;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "CategoryItemServlet", urlPatterns = "/uni/home/category/mutli")
public class CategoryItemServlet extends HttpServlet {
    CategoryItemService service = null;
    @Override
    public void init(ServletConfig config) throws ServletException {
        service = new CategoryItemServiceImpl();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1、创建out对象
        PrintWriter out = response.getWriter();
        // 2、获取opr请求参数
        String opr = request.getParameter("opr");
        AjaxResult result = null;
        if ("list".equals(opr)) {
            // 3、调用service中的方法
            List<CategoryItem> list = service.getOneLevelCategory();
            result = AjaxResult.success("前台分类列表加载成功!", list);
        } else if ("findAll".equals(opr)) {
            List<CategoryItem> list = service.getCategoryAndGoods();
            result = AjaxResult.success("一级分类列表加载成功!", list);
        }
        // 将result对象转换成JSON字符串再响应到小程序端
        out.print(JSONArray.toJSONString(result));
        out.flush();
        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
